package com.sencorsta.ids.core.tcp.socket;



import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;

import io.netty.channel.Channel;

/**
 * 描述：网络报文处理基类
 * @author ICe
 */
public abstract class NetHandler implements Cloneable{

	public NetHandler() {
		ClientEvent handler = this.getClass().getAnnotation(ClientEvent.class);
		if (handler != null) {
			this.type = handler.type();
		}
	}
	
	private Channel channel;

	protected String userId;

	/** 协议编号|类型 */
	private short type;

	/** 获取协议编号|类型 */
	public short getType() {
		return type;
	}

	/** 绑定会话 */
	public void bindChannel(Channel channel) {
		this.channel = channel;
	}

	/** 绑定USERID */
	public void bindUserId(String userId) {
		this.userId = userId;
	}
	
	public Channel channel() {
		return this.channel;
	}

	/** 直接写入，用于非广播消息 */
	public void write(RpcMessage message) {
		//Out.debug("开始write!!!!!!!!!");
		if (channel != null) {
			channel.writeAndFlush(message);
		}else {
			Out.debug("write时channel为空,取消发送");
		}
	}
	
	/**
	 * 处理
	 * @param pak
	 *            待处理包，封装了请求类型以及请求内容
	 * @return 处理结果成功与否
	 */
	public abstract void execute(RpcMessage message);

	public boolean isGateHandler() {
		return false;
	}

	public int getRunIndex() {
		return 0;
	}

	@Override
	public Object clone() {
		NetHandler netHandler = null;
		try{
			netHandler = (NetHandler)super.clone();
		}catch(CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return netHandler;
	}

}
